package com.ccrego.haiyi.app;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ccrego.haiyi.R;
import com.ccrego.haiyi.account.AccountManager;
import com.ccrego.haiyi.common.web.CommonWebviewFragment;
import com.ccrego.haiyi.common.web.cache.NativeWebService;
import com.ccrego.haiyi.common.web.cache.UrlMessage;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.frameworkbase.utils.SLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;



public class MainActivity extends BaseActivity {
    private String mUrl;
    private static boolean isExit = false;
    public static boolean isForeground = false;
    private double latitude;
    private double longitude;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private CommonWebviewFragment mWebviewFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMap();
        hideToolbar();
        EventBus.getDefault().register(this);
//        mUrl = "file:///android_asset/www/index.html";
//        mUrl = "http://server.ccrego.com:8081/index";
//        mUrl ="http://haiyi.xmappservice.com/#/index";
//        mWebviewFragment = CommonWebviewFragment.newInstance(mUrl);
//        getSupportFragmentManager().beginTransaction().add(R.id.flytWebview, mWebviewFragment).commit();
//        MyHttpRequest request = new MyHttpRequest(getBaseContext());

        /**
        * 将h5页面本地化
        */
        NativeWebService.requestCacheUrl(this);
//        testGetAppAttrs();

//        String path = FileManager.getWebCachePath(this) + "zygote_web_cache.zip";
//        String toPath = FileManager.getWebCachePath(this) + "zygote_web_cache";
//        FileUtil.copyAssetToSDCard(getAssets(), "www/zygote_web_cache.zip", path);

//        ZipExtractor zipExtractor = new ZipExtractor(this,
//                path, toPath,
//                new ZipExtractor.OnExtractListener() {
//                    @Override
//                    public void onProgressUpdate(long currSize) {
//                        SLog.e("onProgressUpdate currSize == " + currSize);
//                    }
//                    @Override
//                    public void onComplete(long totalSize) {
//                        SLog.e("onComplete totalSize == " + totalSize);
//                    }
//
//                    @Override
//                    public void onFailure(int errorCode, long totalSize,
//                                          long currSize) {
////                        SLog.e("onFailure errorCode == " + errorCode + "totalSize" + totalSize);
//                    }
//
//                    @Override
//                    public void onCaculateTotalSize(long totalSize) {
//                        SLog.e("onCaculateTotalSize totalSize == " + totalSize);
//                    }
//                });
//        zipExtractor.execute();
    }

    private void initMap() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplication());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(4000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //启动定位
        mLocationClient.startLocation();
    }
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    latitude = amapLocation.getLatitude();
                    longitude = amapLocation.getLongitude();
//                    EventBus.getDefault().post(new LocationCallback(s));
                    AccountManager.getCurrentAccount().setLocationPosition(latitude, longitude);
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                    //可在其中解析amapLocation获取相应内容。
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                    EasyToast.showToast(getContext(), amapLocation.getErrorInfo());
                }
            }
        }
    };


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public static void start(Activity activity){
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        return layoutInflater.inflate(R.layout.activity_main, null);
    }


    void testGetAppAttrs() {
//        TypedArray typedArray1 = obtainStyledAttributes(R.styleable.IconTextArrowButton);
        TypedArray typedArray1 = obtainStyledAttributes(null,R.styleable.BadgeRadioButton,R.attr.badgeRadioButtonStyle,0);
        float drawHeight = typedArray1.getDimension(R.styleable.BadgeRadioButton_drawableHeight, -1.0f);
        Log.e("vivi", "   textSize  ==  " + drawHeight);
        typedArray1.recycle();

        TypedArray typedArray = obtainStyledAttributes(R.styleable.vidroid);
        float textSize1 = typedArray.getDimension(R.styleable.vidroid_textSize1, -1.0f);
        Log.e("vivi", "   textSize1  ==  " + textSize1);
        typedArray.recycle();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(!isExit) {
                isExit = true;
                Toast.makeText(this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            } else {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);//退出程序
//                           finish();
            }
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUrlFound(UrlMessage urlMessage) {
        SLog.e("vivi", "url == " + urlMessage.url);
        mUrl = urlMessage.url;
//        mWebviewFragment.getWebview().loadUrl(mUrl);
        mWebviewFragment = CommonWebviewFragment.newInstance(mUrl);
        getSupportFragmentManager().beginTransaction().add(com.pachong.android.framework.R.id.flytWebview, mWebviewFragment).commit();

    }
}
